package com.ruoyi.service;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
public class DeepSeekSpeechRecognition {

    private static final String API_KEY = "sk-582e9aaf6d374ede8496cea5a1fc5744";
    private static final String API_URL = "https://api.deepseek.com/v1/speech/asr";

    public static void main(String[] args) throws IOException {
        File audioFile = new File("d://1835-1.wav");
        String result = recognizeSpeech(audioFile);
        System.out.println("识别结果: " + result);
    }

    public static String recognizeSpeech(File audioFile) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();

        // 构建 multipart/form-data 请求
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("audio", audioFile.getName(),
                        RequestBody.create(audioFile, MediaType.parse("audio/wav")))
                .addFormDataPart("language", "zh-CN") // 中文普通话
                .build();

        Request request = new Request.Builder()
                .url(API_URL)
                .post(requestBody)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "multipart/form-data")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " - " + response.message());
            }

            // 解析返回的JSON（假设返回格式为 {"text": "识别结果"}）
            String responseBody = response.body().string();
            return parseResponse(responseBody);
        }
    }

    private static String parseResponse(String jsonResponse) {
        // 这里可以使用 JSON 解析库（如 Gson/Jackson）
        // 简单示例使用字符串处理
        if (jsonResponse.contains("\"text\":")) {
            return   jsonResponse;//  jsonResponse.split("\"text\":\"") .toString();//.split("\"");
        }
        return "解析失败";
    }
}